package handler

import (
	"context"
	"errors"
	"math/rand"
	"server/basic/dao"
	"server/basic/pkg"
	"server/basic/proto/user"
	"strconv"
)

type UserServer struct {
	user.UnimplementedUserServerServer
}

func (s *UserServer) UserLogin(_ context.Context, req *user.UserLoginReq) (*user.UserLoginResp, error) {
	where, err := dao.UserWhere(req.Name)
	if err != nil {
		return nil, err
	}
	if where.Id == 0 {
		login := dao.RedisLogin(req.Mobile, req.Code)
		if !login {
			return nil, errors.New("验证码错误")
		}
		register, err := dao.UserRegister(req.Name, req.Mobile, req.Password)
		if err != nil {
			return nil, err
		}
		if register.Id == 0 {
			return nil, errors.New("登录失败")
		}
		register.Id = where.Id
	}

	return &user.UserLoginResp{UserId: int32(where.Id)}, nil
}
func (s *UserServer) UserSuccess(_ context.Context, req *user.UserSuccessReq) (*user.UserSuccessResp, error) {
	code := rand.Intn(9000) + 1000
	_, err := pkg.ALiYun(req.Mobile, strconv.Itoa(code))
	if err != nil {
		return nil, err
	}
	if !dao.RedisSuccess(req.Mobile, code) {
		return nil, errors.New("验证码发送失败")
	}

	return &user.UserSuccessResp{Success: true}, nil
}
